package sniff.diller;

import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
import sniff.pack.CommonIPChildPacket;
import sniff.pack.MyIPv6Packet;
import util.ByteUtil;

public class IPv6PacketDiller {
	public static MyIPv6Packet dill(Packet pack) {
		IPPacket ipPack = (IPPacket) pack;
		byte[] head = ipPack.header;
		byte[] data = ipPack.data;
		int startIndex = 14;
		CommonHeadDiller hd = new CommonHeadDiller(head);
		String sourceMAC = hd.getSourceMAC();
		String destinationMAC = hd.getDestinationMAC();
		String type = hd.getType();

		String version = "IPv6";
		if (ByteUtil.getFourBit(head[startIndex], false) != 6) {
			version = "error";
		}
		if(ipPack.version!=6) {
			version = "error!";
		}
		String trafficClass = "0x" + ByteUtil.byteToHexString(head[startIndex]).substring(1)
				+ ByteUtil.byteToHexString(head[startIndex + 1]).substring(0, 1);
		String flowLabel = "0x" + ByteUtil.byteToHexString(head[startIndex + 1]).substring(1)
				+ ByteUtil.byteToHexString(head[startIndex + 2]) + ByteUtil.byteToHexString(head[startIndex + 3]);
		int payLoadLen = ByteUtil.unionByte(head[startIndex + 4], head[startIndex + 5]);
		CommonIPChildPacket childPacket = null;
		String protocol = "IPv6";
		switch (ByteUtil.byteToInt(head[startIndex + 6])) {
		case 1:
			protocol = "ICMP";
			childPacket = ICMPPacketDiller.dill(pack);
			break;
		case 2:
			protocol = "IGMP";
			break;
		case 6:
			protocol = "TCP";
			childPacket = TCPPacketDiller.dill(pack);
			break;
		case 8:
			protocol = "EGP";
			break;
		case 9:
			protocol = "IGP";
			break;
		case 17:
			protocol = "UDP";
			childPacket = UDPPacketDiller.dill(pack);
			break;
		case 41:
			protocol = "IPv6";
			break;
		case 50:
			protocol = "ESP";
			break;
		case 89:
			protocol = "OSPF";
			childPacket = OSPFPacketDiller.dill(pack);
			break;
		default:
			break;
		}
		int hopLimit = ByteUtil.byteToInt(head[startIndex + 7]);
		String sourceIP = "";
		for (int i = startIndex + 8; i < startIndex + 24; i += 2) {
			sourceIP += ByteUtil.byteToHexString(head[i]) + ByteUtil.byteToHexString(head[i + 1]) + ":";
		}
		sourceIP = sourceIP.substring(0, sourceIP.length() - 1);
		String destinationIP = "";
		for (int i = startIndex + 24; i < startIndex + 40; i += 2) {
			destinationIP += ByteUtil.byteToHexString(head[i]) + ByteUtil.byteToHexString(head[i + 1]) + ":";
		}
		destinationIP = destinationIP.substring(0, destinationIP.length() - 1);
		String info = "";
		MyIPv6Packet ipv6Pack = new MyIPv6Packet(sourceMAC, destinationMAC, type, payLoadLen + 40, info, head, data,
				version, trafficClass, flowLabel, payLoadLen, protocol, hopLimit, sourceIP, destinationIP);
		ipv6Pack.setChildPacket(childPacket);
		return ipv6Pack;

	}
}
